#!/usr/bin/env bash

# This script is used for setup k8s+calico all configurations in multi-nodes, one or more master(s)
#
# FileName     : dockerbuild.sh
# Path         : /app/ghxt/Dockerfile
# Author       : ymliu
# Create Date  : 2021-05-31 17:10
# WorkFlow     : To build docker image & export to ftp automatically.
#                mv -f /home/xtuser607/@delete/${1}.jar /app/ghxt/Dockerfile/
#                chown root:root ${1}.jar
#                docker build -f xx.dockerfile -t ghxt/xx:dev-today-$2
#                docker save xxx.image.tar
#                gzip ghxt/xxx.image.tar
#                cp ghxt/xxx.image.tar.gz /home/...
#                chown xtuser607 /home/...

# ----------------------------------------------------------------
function show_usage()
{
  echo "Usage: build docker image and push to ftp directory"
  echo ""
  echo "  dockerbuild.sh <module> <version> <path>"
  echo ""
  echo "  <module>  : Such as ghxt-fi, sgcc, etc. Indicates ghxt-fi.jar, <path>/ghxt-fi:dev-1114-123 ."
  echo "  <version> : As ending of tag for image."
  echo "  <path>    : As path of image. E.g. <path>/<image>:<tag> -> ghxt/ghxt-fi:dev-1114-123"
  echo ""
  echo "For example: dockerbuild.sh ghxt-fi 110"
  echo "  As command upon, it will move ghxt-fi.jar, build image ghxt/ghxt-fi:dev-1114-110, mv file ghxt-fi_dev...image.tar.gz to ftp."
}

# ---- main ----
if [ $# -lt 2 ]; then
  show_usage
  exit 1
fi

set -ex

declare -r MODULE=${1}
declare -r VERSION=${2}
declare -r IMAGEPATH=${3:-ghxt}
declare -r JAR=${MODULE}.jar

pushd /app/Dockerfile >/dev/null

# remove old jar
if [ -f ${JAR} ]; then
  echo "Removing old jar ${JAR}"
  rm -f ./${JAR}
fi
# mv jar here
echo "mv ${JAR} ..."
mv -f "/home/xtuser607/@delete/${JAR}" ./
chown root:root ./${JAR}

# docker build
echo "building docker image..."
declare -r DOCKERFILE="${MODULE}.dockerfile"
declare -r DATE=$(date +%m%d)
declare -r TAG=dev-${DATE}-${VERSION}
declare IMAGE=${IMAGEPATH}/${MODULE}:${TAG}
docker build -f ${DOCKERFILE} -t ${IMAGE} .

# docker save
echo "saving docker image ..."
declare TAR_FILE=${MODULE}_${TAG}.image.tar
docker save ${IMAGE} -o ${TAR_FILE}

# gzip
echo "gziping docker image..."
gzip ${TAR_FILE}
declare -r GZ_FILE=${TAR_FILE}.gz

echo +
echo "Docker image saved as ${GZ_FILE}"

# mv gz_file to ftp
echo "mv *.tar.gz file to ftp..."
cp -f ${GZ_FILE} /home/xtuser607/@delete
mv -f ${GZ_FILE} /app/images/
chown xtuser607 /home/xtuser607/@delete/${GZ_FILE}

popd >/dev/null
